package org.hepeng.workx.spring.security.oauth2;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.security.oauth2.resource.DefaultUserInfoRestTemplateFactory;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoRestTemplateCustomizer;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;

import java.util.ArrayList;
import java.util.List;

/**
 * @author he peng
 */
public class LoadBalancerUserInfoRestTemplateFactory extends DefaultUserInfoRestTemplateFactory {


    private LoadBalancerClient loadBalancerClient;

    public LoadBalancerUserInfoRestTemplateFactory(ObjectProvider<List<UserInfoRestTemplateCustomizer>> customizers,
                                                   ObjectProvider<OAuth2ProtectedResourceDetails> details,
                                                   ObjectProvider<OAuth2ClientContext> oauth2ClientContext,
                                                   LoadBalancerClient loadBalancerClient) {
        super(customizers, details, oauth2ClientContext);
        this.loadBalancerClient = loadBalancerClient;
    }

    @Override
    public OAuth2RestTemplate getUserInfoRestTemplate() {
        OAuth2RestTemplate userInfoRestTemplate = super.getUserInfoRestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new LoadBalancerInterceptor(this.loadBalancerClient));
        userInfoRestTemplate.setInterceptors(interceptors);
        return userInfoRestTemplate;
    }
}
